package com.egao.orderB.biz.impl;

import com.egao.common.core.damon.constant.UserConstant;
import com.egao.common.core.damon.results.BaseDao;
import com.egao.common.core.damon.results.PageResult2;
import com.egao.common.core.damon.utils.PinyinUtils;
import com.egao.common.core.damon.utils.Utils;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.entity.User;
import com.egao.orderB.biz.AddressBiz;
import com.egao.orderB.entity.Address;
import com.egao.orderB.entity.AddressTemp;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 数据层实现类
 * @author : Doman
 * @date : 2020-06-22 10:37:54
 * @version ：1.0
 */
@Repository
public class AddressBizImpl extends BaseDao implements AddressBiz {

	@Override
	public JsonResult list(PageResult2<T> page, Address address, User loginUser) throws Exception {
		Map<String, String> map  = new HashMap<String, String>();
		RowMapper<Address> rm = new BeanPropertyRowMapper<Address>(Address.class);
		StringBuffer sql = new StringBuffer("select a.id,a.organization_id,a.customer_id,ct.name customerName");
        sql.append(",a.province,a.city,a.district,a.town");
        sql.append(",a.contact,a.contact_phone,a.pinyin");
		sql.append(",a.address,a.dock,a.box_type,a.price,a.driver_price,a.state");
		sql.append(",a.remark,a.create_time,a.create_user,a.update_time");
		sql.append(",a.update_user");
//		sql.append(",caf.faddress,caf.fphone,caf.fstate");
        sql.append(",sognz.organization_name organizationName,suser.username createName ");
        sql.append(" from chf_address a ");
        sql.append(" inner join sys_user suser on suser.user_id=a.create_user ");
        sql.append(" inner join sys_organization sognz on sognz.organization_id=a.organization_id ");
        sql.append(" inner join chf_customer ct on ct.id=a.customer_id ");
//        sql.append(" left join chf_address_factory caf on caf.address_id=a.id and caf.deleted=0 ");
        sql.append(" where a.deleted=0 and sognz.deleted=0 ");
		if(loginUser.getUserId() != UserConstant.ADMIN_ID){
			sql.append(" and a.organization_id=:tableOrganizationId ");
			map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
    	if(Utils.isNotEmpty(address)){
			if(Utils.isNotEmpty(address.getCustomerId())){
				sql.append(" and a.customer_id=:customer_id ");
				map.put("customer_id", address.getCustomerId());
			}
			if(Utils.isNotEmpty(address.getCustomerName())){
				sql.append(" and ct.name=:customer_name ");
				map.put("customer_name", address.getCustomerName());
			}
			if(Utils.isNotEmpty(address.getProvince())){
				sql.append(" and (instr(a.province,:province)>0 or instr(a.pinyin,:province)>0 ) ");
				map.put("province", address.getProvince().toLowerCase());
			}
			if(Utils.isNotEmpty(address.getCity())){
				sql.append(" and (instr(a.city,:city)>0 or instr(a.pinyin,:city)>0 ) ");
				map.put("city", address.getCity().toLowerCase());
			}
			if(Utils.isNotEmpty(address.getDistrict())){
				sql.append(" and (instr(a.district,:district)>0 or instr(a.pinyin,:district)>0 ) ");
				map.put("district", address.getDistrict().toLowerCase());
			}
			if(Utils.isNotEmpty(address.getTown())){
				sql.append(" and (instr(a.town,:town)>0 or instr(a.pinyin,:town)>0 ) ");
				map.put("town", address.getTown().toLowerCase());
			}
			if(Utils.isNotEmpty(address.getBoxType())){
				sql.append(" and instr(a.box_type,:box_type)>0 ");
				map.put("box_type", address.getBoxType());
			}
			if(Utils.isNotEmpty(address.getDock())){
				sql.append(" and instr(a.dock,:dock)>0 ");
				map.put("dock", address.getDock());
			}
			if(Utils.isNotEmpty(address.getAddress())){
				sql.append(" and (instr(a.address,:address)>0 or instr(a.pinyin,:address)>0 ) ");
				map.put("address", address.getAddress().toLowerCase());
			}
			if(Utils.isNotEmpty(address.getState())){
				sql.append(" and instr(a.state,:state)>0 ");
				map.put("state", address.getState());
			}
			if(Utils.isNotEmpty(address.getSort())&&Utils.isNotEmpty(address.getOrder())){
                sql.append(" order by a."+address.getSort()+" "+address.getOrder());
            } else {
                sql.append(" order by a.create_time desc");
            }
		}
		return jsonResult(getPageQueryList(page, sql.toString(), map, rm));
	}

	@Override
	public List<Address> list(Address address, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		RowMapper<Address> rm = new BeanPropertyRowMapper<Address>(Address.class);
        StringBuffer sql = new StringBuffer("select a.id,a.organization_id,a.customer_id,ct.name customerName");
        sql.append(",a.province,a.city,a.district,a.town");
		sql.append(",a.contact,a.contact_phone,a.pinyin");
		sql.append(",a.address,a.dock,a.box_type,a.price,a.driver_price,a.state");
		sql.append(",a.remark,a.create_time,a.create_user,a.update_time");
		sql.append(",a.update_user");
//		sql.append(",caf.faddress,caf.fphone,caf.fstate");
        sql.append(",sognz.organization_name organizationName,suser.username createName ");
        sql.append(" from chf_address a ");
        sql.append(" inner join sys_user suser on suser.user_id=a.create_user ");
        sql.append(" inner join sys_organization sognz on sognz.organization_id=a.organization_id ");
		sql.append(" inner join chf_customer ct on ct.id=a.customer_id ");
//		sql.append(" left join chf_address_factory caf on caf.address_id=a.id and caf.deleted=0 ");
		sql.append(" where a.deleted=0 and sognz.deleted=0 ");
		if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            sql.append(" and a.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
    	if(Utils.isNotEmpty(address)){
			if(Utils.isNotEmpty(address.getCustomerId())){
				sql.append(" and a.customer_id=:customer_id ");
				map.put("customer_id", address.getCustomerId());
			}
			if(Utils.isNotEmpty(address.getCustomerName())){
				sql.append(" and ct.name=:customer_name ");
				map.put("customer_name", address.getCustomerName());
			}
			if(Utils.isNotEmpty(address.getProvince())){
				sql.append(" and (instr(a.province,:province)>0 or instr(a.pinyin,:province)>0 ) ");
				map.put("province", address.getProvince().toLowerCase());
			}
			if(Utils.isNotEmpty(address.getCity())){
				sql.append(" and (instr(a.city,:city)>0 or instr(a.pinyin,:city)>0 ) ");
				map.put("city", address.getCity().toLowerCase());
			}
			if(Utils.isNotEmpty(address.getDistrict())){
				sql.append(" and (instr(a.district,:district)>0 or instr(a.pinyin,:district)>0 ) ");
				map.put("district", address.getDistrict().toLowerCase());
			}
			if(Utils.isNotEmpty(address.getTown())){
				sql.append(" and (instr(a.town,:town)>0 or instr(a.pinyin,:town)>0 ) ");
				map.put("town", address.getTown().toLowerCase());
			}
			if(Utils.isNotEmpty(address.getBoxType())){
				sql.append(" and instr(a.box_type,:box_type)>0 ");
				map.put("box_type", address.getBoxType());
			}
			if(Utils.isNotEmpty(address.getAddress())){
				sql.append(" and (instr(a.address,:address)>0 or instr(a.pinyin,:address)>0 ) ");
				map.put("address", address.getAddress().toLowerCase());
			}
			if(Utils.isNotEmpty(address.getDock())){
				sql.append(" and instr(a.dock,:dock)>0 ");
				map.put("dock", address.getDock());
			}

			if(Utils.isNotEmpty(address.getState())){
				sql.append(" and instr(a.state,:state)>0 ");
				map.put("state", address.getState());
			}
			if(Utils.isNotEmpty(address.getSort())&&Utils.isNotEmpty(address.getOrder())){
				sql.append(" order by a."+address.getSort()+" "+address.getOrder());
			} else {
				sql.append(" order by a.create_time desc");
			}
		}
		getMapParameter(sql, map);
		return jdbcTemplate.query(sql.toString(),map, rm);
	}

	@Override
	public List<Address> searchAddressFee(Address address, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		RowMapper<Address> rm = new BeanPropertyRowMapper<Address>(Address.class);
        StringBuffer sql = new StringBuffer("select a.id,a.organization_id,a.customer_id,ct.name customerName");
        sql.append(",a.province,a.city,a.district,a.town");
		sql.append(",a.contact,a.contact_phone,a.pinyin");
		sql.append(",a.address,a.dock,a.box_type,a.price,a.driver_price,a.state,'address' ftype");
		sql.append(",a.remark,a.create_time,a.create_user,a.update_time");
		sql.append(",a.update_user");
//		sql.append(",caf.faddress,caf.fphone,caf.fstate");
        sql.append(",sognz.organization_name organizationName,suser.username createName ");
        sql.append(" from chf_address a ");
        sql.append(" inner join sys_user suser on suser.user_id=a.create_user ");
        sql.append(" inner join sys_organization sognz on sognz.organization_id=a.organization_id ");
		sql.append(" inner join chf_customer ct on ct.id=a.customer_id ");
//		sql.append(" left join chf_address_factory caf on caf.address_id=a.id and caf.deleted=0 ");
		sql.append(" where a.deleted=0 and sognz.deleted=0 ");
		if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            sql.append(" and a.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
		sql.append(" and a.customer_id=:customer_id ");
		map.put("customer_id", address.getCustomerId());
		sql.append(" and (instr(ct.name,:customer_name)>0 ");
		sql.append(" or instr(a.province,:customer_name)>0 ");
		sql.append(" or instr(a.city,:customer_name)>0 ");
		sql.append(" or instr(a.district,:customer_name)>0 ");
		sql.append(" or instr(a.town,:customer_name)>0 ");
		sql.append(" or instr(a.box_type,:customer_name)>0 ");
		sql.append(" or instr(a.contact,:customer_name)>0 ");
		sql.append(" or instr(a.contact_phone,:customer_name)>0 ");
		sql.append(" or instr(a.address,:customer_name)>0 ");
		sql.append(" or instr(CONCAT(a.province,a.city, a.district,a.town,a.address),:customer_name)>0 ");
		sql.append(" or instr(a.pinyin,:customer_name)>0 ");
		sql.append(" ) ");

		if(Utils.isNotEmpty(address.getDock())){
			sql.append(" and instr(a.dock,:dock)>0 ");
			map.put("dock", address.getDock());
		}
		map.put("customer_name", address.getCustomerName());
		sql.append(" order by a.create_time desc");
		getMapParameter(sql, map);
		return jdbcTemplate.query(sql.toString(),map, rm);
	}

	@Override
	public List<AddressTemp> searchCustomerAddress(Address address, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		RowMapper<AddressTemp> rm = new BeanPropertyRowMapper<AddressTemp>(AddressTemp.class);
        StringBuffer sql = new StringBuffer("select a.id");
		sql.append(",a.contact,a.contact_phone");
		sql.append(",a.address,a.box_type,a.price");
		sql.append(",'addrress' addressType ");
        sql.append(" from chf_address a ");
        sql.append(" inner join sys_user suser on suser.user_id=a.create_user ");
        sql.append(" inner join sys_organization sognz on sognz.organization_id=a.organization_id ");
		sql.append(" inner join chf_customer ct on ct.id=a.customer_id ");
//		sql.append(" left join chf_address_factory caf on caf.address_id=a.id and caf.deleted=0 ");
		sql.append(" where a.deleted=0 and sognz.deleted=0 ");
		if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            sql.append(" and a.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
		sql.append(" and a.customer_id=:customer_id ");
		map.put("customer_id", address.getCustomerId());
		sql.append(" and (instr(ct.name,:customer_name)>0 ");
		sql.append(" or instr(a.province,:customer_name)>0 ");
		sql.append(" or instr(a.city,:customer_name)>0 ");
		sql.append(" or instr(a.district,:customer_name)>0 ");
		sql.append(" or instr(a.town,:customer_name)>0 ");
		sql.append(" or instr(a.box_type,:customer_name)>0 ");
		sql.append(" or instr(a.contact,:customer_name)>0 ");
		sql.append(" or instr(a.contact_phone,:customer_name)>0 ");
		sql.append(" or instr(a.address,:customer_name)>0 ");
		sql.append(" or instr(CONCAT(a.province,a.city, a.district,a.town,a.address),:customer_name)>0 ");
		sql.append(" or instr(a.pinyin,:customer_name)>0 ");
		sql.append(" ) ");

		if(Utils.isNotEmpty(address.getDock())){
			sql.append(" and instr(a.dock,:dock)>0 ");
			map.put("dock", address.getDock());
		}
		map.put("customer_name", address.getCustomerName());
		sql.append(" order by a.create_time desc ");
		sql.append("  limit 100");
		getMapParameter(sql, map);
		return jdbcTemplate.query(sql.toString(),map, rm);
	}

	@Override
	public List<Address> dockList(Address address, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		RowMapper<Address> rm = new BeanPropertyRowMapper<Address>(Address.class);
        StringBuffer sql = new StringBuffer("select distinct a.dock");
        sql.append(" from chf_address a ");
        sql.append(" inner join sys_organization sognz on sognz.organization_id=a.organization_id ");
		sql.append(" where a.deleted=0 and sognz.deleted=0 ");
		getMapParameter(sql, map);
		return jdbcTemplate.query(sql.toString(),map, rm);
	}

	@Override
	public Address getById(Address address) {
		RowMapper<Address> rm = new BeanPropertyRowMapper<Address>(Address.class);
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql = new StringBuffer("select a.id,a.organization_id,a.customer_id,ct.name customerName");
        sql.append(",a.province,a.city,a.district,a.town");
		sql.append(",a.contact,a.contact_phone");
		sql.append(",a.address,a.dock,a.box_type,a.price,a.driver_price,a.state");
		sql.append(",a.remark,a.create_time,a.create_user,a.update_time");
		sql.append(",a.update_user");
//		sql.append(",caf.faddress,caf.fphone,caf.fstate");
        sql.append(",sognz.organization_name organizationName,suser.username createName ");
        sql.append(" from chf_address a ");
        sql.append(" inner join sys_user suser on suser.user_id=a.create_user ");
        sql.append(" inner join sys_organization sognz on sognz.organization_id=a.organization_id ");
		sql.append(" inner join chf_customer ct on ct.id=a.customer_id ");
//		sql.append(" left join chf_address_factory caf on caf.address_id=a.id and caf.deleted=0 ");
        sql.append(" where a.deleted=0 and sognz.deleted=0 and a.id=:id ");
		map.put("id", address.getId());
		getMapParameter(sql, map);
		return jdbcTemplate.queryForObject(sql.toString(), map, rm);
	}

	@Override
	public Integer save(Address address, User loginUser) {
		address.setPinyin(PinyinUtils.ToFirstChar(address.getProvince()+address.getCity()+address.getDistrict()+address.getTown()+address.getAddress()));
		GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
		KeyHolder keyHolder=new GeneratedKeyHolder();
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("insert into chf_address (");
        sql.append("organization_id,customer_id,province,city");
		sql.append(",district,town,address,pinyin,dock,contact,contact_phone");
		sql.append(",box_type,price,driver_price,state,remark,create_user,create_time) values ( ");
        sql.append(":organization_id,:customer_id,:province,:city");
		sql.append(",:district,:town,:address,:pinyin,:dock,:contact,:contact_phone");
		sql.append(",:box_type,:price,:driver_price,:state,:remark,:create_user,now())");
        map.put("organization_id", loginUser.getOrganizationId()+ "");
        map.put("customer_id", address.getCustomerId());
        map.put("province", address.getProvince());
        map.put("city", address.getCity());
        map.put("district", address.getDistrict());
        map.put("town", address.getTown());
        map.put("address", address.getAddress());
        map.put("pinyin", address.getPinyin());
        map.put("dock", address.getDock());
        map.put("contact", address.getContact());
        map.put("contact_phone", address.getContactPhone());
        map.put("box_type", address.getBoxType());
        map.put("price", address.getPrice());
        map.put("driver_price", address.getDriverPrice());
        map.put("state", address.getState());
        map.put("remark", address.getRemark());
		map.put("create_user", loginUser.getUserId() + "");
		getMapParameter(sql, map);
		//		System.err.println("受到影响的行数=" + retVal + ",
		int retVal = this.jdbcTemplate.update(sql.toString(), new SqlParameterSource() {
			@Override
			public boolean hasValue(String paramName) {
				return map.containsKey(paramName);
			}
			@Override
			public Object getValue(String paramName) throws IllegalArgumentException {
				return map.get(paramName);
			}
		}, generatedKeyHolder);
		Integer id = generatedKeyHolder.getKey().intValue();
		return id;
	}

	@Override
	public boolean update(Address address, User loginUser) {
//		System.out.println("===="+address.getProvince()+address.getCity()+address.getDistrict()+address.getTown()+address.getAddress());
		address.setPinyin(PinyinUtils.ToFirstChar(address.getProvince()+address.getCity()+address.getDistrict()+address.getTown()+address.getAddress()));
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("update chf_address set ");
        sql.append("province=:province,city=:city,price=:price,driver_price=:driver_price ");
		sql.append(",district=:district,town=:town,address=:address ");
		sql.append(",pinyin=:pinyin,dock=:dock,box_type=:box_type ");
		sql.append(",contact=:contact,contact_phone=:contact_phone ");
		sql.append(",remark=:remark,update_time=now(),update_user=:update_user where id=:id ");
        map.put("province", address.getProvince());
        map.put("city", address.getCity());
        map.put("price", address.getPrice());
        map.put("driver_price", address.getDriverPrice());
        map.put("district", address.getDistrict());
        map.put("town", address.getTown());
        map.put("address", address.getAddress());
        map.put("pinyin", address.getPinyin());
        map.put("dock", address.getDock());
        map.put("box_type", address.getBoxType());
        map.put("contact", address.getContact());
        map.put("contact_phone", address.getContactPhone());
        map.put("remark", address.getRemark());
		map.put("update_user", loginUser.getUserId() + "");
		map.put("id", address.getId());
		getMapParameter(sql, map);
		int count = jdbcTemplate.update(sql.toString(), map);
		return count > 0;
	}

	@Override
	public boolean customerUpdate(Address address, User loginUser) {
		address.setPinyin(PinyinUtils.ToFirstChar(address.getProvince()+address.getCity()+address.getDistrict()+address.getTown()+address.getAddress()));
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("update chf_address set ");
        sql.append("province=:province,city=:city ");
		sql.append(",district=:district,town=:town,address=:address ");
		sql.append(",pinyin=:pinyin,dock=:dock,box_type=:box_type ");
		sql.append(",contact=:contact,contact_phone=:contact_phone ");
		sql.append(",remark=:remark,update_time=now(),update_user=:update_user where id=:id ");
        map.put("province", address.getProvince());
        map.put("city", address.getCity());
        map.put("district", address.getDistrict());
        map.put("town", address.getTown());
        map.put("address", address.getAddress());
        map.put("pinyin", address.getPinyin());
        map.put("dock", address.getDock());
        map.put("box_type", address.getBoxType());
		map.put("contact", address.getContact());
		map.put("contact_phone", address.getContactPhone());
        map.put("remark", address.getRemark());
		map.put("update_user", loginUser.getUserId() + "");
		map.put("id", address.getId());
		getMapParameter(sql, map);
		int count = jdbcTemplate.update(sql.toString(), map);
		return count > 0;
	}

	//现在没有用
	@Override
	public boolean updatePrice(Address address, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("update chf_address set ");
		sql.append("price=:price,driver_price=:driver_price ");
		sql.append(",update_time=now(),update_user=:update_user where id=:id ");
        map.put("price", address.getPrice());
        map.put("driver_price", address.getDriverPrice());
		map.put("update_user", loginUser.getUserId() + "");
		map.put("id", address.getId());
		getMapParameter(sql, map);
		int count = jdbcTemplate.update(sql.toString(), map);
		return count > 0;
	}

	@Override
	public boolean updateState(Address address, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("update chf_address set ");
		sql.append("state=:state ");
		sql.append(",update_time=now(),update_user=:update_user where id=:id ");
        map.put("state", address.getState());
		map.put("update_user", loginUser.getUserId() + "");
		map.put("id", address.getId());
		getMapParameter(sql, map);
		int count = jdbcTemplate.update(sql.toString(), map);
		return count > 0;
	}

	@Override
	public boolean remove(Address address, User loginUser) {
		int count = 0;
		Map<String, String> map = null;
		if(address.getId().length()>0){
			for(String ID : address.getId().split(",")){
				map  = new HashMap<String, String>();
				if(ID==null || ID.equals("")){ break; }
				StringBuffer sql =new StringBuffer("update chf_address set deleted=1" +
						",update_user=:update_user, update_time=now() "
						+ " where id =:id ");
				map.put("update_user", loginUser.getUserId() + "");
				map.put("id", ID);
				getMapParameter(sql, map);
				count = jdbcTemplate.update(sql.toString(),map);
			}
		}
		return count > 0;
	}
}
